
package saxon.gui.model;

import java.io.IOException;
import javax.swing.SwingWorker;
import org.apache.log4j.Logger;
import saxon.gui.view.api.XView;

/**
 *
 * @author lennyn
 */
public class ShellExecutor {
	private final static Logger logger = Logger.getLogger(ShellExecutor.class);
	private final XView view;

	public ShellExecutor(XView view) {
		this.view = view;
	}

	public void executeCommand(String shellCommand, String lastQuery) {
		ShellWorker worker = new ShellWorker(shellCommand, lastQuery);
		worker.execute();
	}

	private class ShellWorker extends SwingWorker<String, String> {

		private final String lastQuery;
		private final String shellCommand;
		private String res;

		private Exception exception = null;

		public ShellWorker(String lastQuery, String shellCommand) {
			this.lastQuery = lastQuery;
			this.shellCommand = shellCommand;
		}

		@Override
		protected String doInBackground() {
			String text = view.getOutputText();
			ProcessRunner runner = new ProcessRunner("/bin/bash", "-c", shellCommand);
			try {
				res = runner.run(text);
				return res;
			}
			catch (IOException ex) {
				exception = ex;
				logger.error("failed to run shell command", ex);
				return text;
			}
		}

		@Override
		public void done() {
			if (exception == null)
				view.showShellCommandResult(lastQuery, shellCommand, res);
			else
				view.showError(exception.getMessage());
			view.setRunning(false);
		}
		
	}
}
